<script setup lang="ts" name="SystemTenant">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { getIntDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
import { dateFormatter, dateTimeFormatter } from '@/utils/dateUtil'
import { TenantApi } from '@/api/system/tenant'
import { TenantPackageApi, TenantPackageType } from '@/api/system/tenantPackage'
import { dataToFile } from '@/components/Excel/src/helper'
import TenantForm from './TenantForm.vue'
import { checkPermit, computedOperateWidth } from '@/utils/permit'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const total = ref(0) // 列表的总页数
const list = ref([]) // 表格数据
const queryLoading = ref(false) // 列表加载中：1）列表数据加载；2）查询按钮禁用；3）重置按钮禁用
const queryParams = ref({
  pageIndex: 1,
  pageSize: 20,
  name: '',
  contactName: '',
  contactMobile: '',
  create_time: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const packageList = ref([] as TenantPackageType[]) // 租户套餐
const isExpanded = ref(false) // 查询条件折叠展开

const expandChange = () => {
  isExpanded.value = !isExpanded.value
}

/** 查询列表 */
const getList = async () => {
  queryLoading.value = true
  try {
    const data = await TenantApi.page(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    queryLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageIndex = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.pageIndex = 1
  queryParams.value.pageSize = 20
  queryParams.value.name = ''
  queryParams.value.contactName = ''
  queryParams.value.contactMobile = ''
  queryParams.value.create_time = undefined
  queryParams.value.status = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TenantApi.delete(id)
    message.success(t('message.del', 'success'))
    // 刷新列表
    await getList()
  } catch { }
}

const ExcelExportDialogRef = ref()

const filedList = ref([
  { key: 'id', value: 'ID' },
  { key: 'name', value: t('sys.tenant', 'name') },
  { key: 'contactName', value: t('sys.tenant', 'contactName') },
  { key: 'contactMobile', value: t('sys.tenant', 'contactMobile') },
  { key: 'domain', value: t('sys.tenant', 'domain') },
  { key: 'packageId', value: t('sys.tenant', 'packageId') },
  { key: 'expireTime', value: t('sys.tenant', 'expireTime') },
  { key: 'status', value: t('common', 'status') },
  { key: 'remark', value: t('common', 'remark') }
])
/** 导出按钮操作 */
const handleExport = async () => {
  ExcelExportDialogRef.value.open()
}

const exportDone = async (res) => {
  if (res.dataScope === 1) {
    dataToFile(list.value, res)
  } else if (res.dataScope === 3) {
    const allList = await TenantApi.export(queryParams.value)
    dataToFile(allList, res)
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载套餐列表
  packageList.value = await TenantPackageApi.simple()
})
</script>

<template>
  <PageCard>
    <ContentFormTable>
      <template #header>
        <ElForm ref="queryFormRef" :model="queryParams" :inline="true">
          <ElFormItem :label="t('sys.tenant', 'name')" prop="name" class="!w-240px">
            <el-input v-model="queryParams.name" :placeholder="t('sys.tenant.rules', 'name')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem v-if="isExpanded" :label="t('sys.tenant', 'contactName')" prop="contactName" class="!w-240px">
            <el-input v-model="queryParams.contactName" :placeholder="t('sys.tenant.rules', 'contactName')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem v-if="isExpanded" :label="t('sys.tenant', 'contactMobile')" prop="contactMobile" class="!w-240px">
            <el-input v-model="queryParams.contactMobile" :placeholder="t('sys.tenant.rules', 'contactMobile')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem v-if="isExpanded" :label="t('common', 'status')" prop="status">
            <el-select v-model="queryParams.status" class="!w-160px" clearable :placeholder="t('sys.tenant.rules', 'status')" @change="handleQuery">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </ElFormItem>
          <ElFormItem v-if="isExpanded" :label="t('common', 'createTime')" prop="create_time">
            <el-date-picker
              v-model="queryParams.create_time"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              clearable
              :start-placeholder="t('common', 'startDate')"
              :end-placeholder="t('common', 'endDate')"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleQuery" />
          </ElFormItem>
          <ElFormItem>
            <el-button type="primary" :disabled="queryLoading" icon="Search" @click="handleQuery">{{ t('action',
              'search') }}</el-button>
            <el-button icon="Refresh" :disabled="queryLoading" @click="resetQuery">{{ t('action', 'reset')
            }}</el-button>
          </ElFormItem>
          <ElFormItem>
            <el-button v-if="checkPermit(['system:tenant:create'])" type="success" icon="Plus" @click="openForm('create')">{{ t('action', 'create') }}</el-button>
            <CButton v-if="checkPermit(['system:tenant:export'])" type="warning" :disabled="queryLoading" :onClick="handleExport" preIcon="ri:export-line" :title="t('action', 'export')" />
            <CButton text type="info" :disabled="queryLoading" :onClick="expandChange" :preIcon="isExpanded ? 'ep:arrow-up' : 'ep:arrow-down'" :title="isExpanded ? t('action', 'fold') : t('action', 'unfold')" />
          </ElFormItem>
        </ElForm>
      </template>
      <template #content>
        <el-table v-loading="queryLoading && systemConfig.loadingType === 'module'" :data="list" border>
          <el-table-column type="index" :label="t('common', 'index')" width="60" align="center" />
          <el-table-column prop="name" :label="t('sys.tenant', 'name')" show-overflow-tooltip align="center" />
          <el-table-column prop="packageId" :label="t('sys.tenant', 'packageId')" show-overflow-tooltip width="160" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.packageId === 0" type="danger">{{ t('sys.tenant', 'admin') }}</el-tag>
              <template v-else>
                <template v-for="item in packageList">
                  <el-tag v-if="item.id === scope.row.packageId" :key="item.id" type="success">
                    {{ item.name }}
                  </el-tag>
                </template>
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="contactName" :label="t('sys.tenant', 'contactName')" show-overflow-tooltip width="160" align="center" />
          <el-table-column prop="contactMobile" :label="t('sys.tenant', 'contactMobile')" show-overflow-tooltip width="160" align="center" />
          <el-table-column prop="domain" :label="t('sys.tenant', 'domain')" show-overflow-tooltip width="160" align="center" />
          <el-table-column prop="expireTime" :label="t('sys.tenant', 'expireTime')" :formatter="dateTimeFormatter" align="center" />
          <el-table-column prop="status" :label="t('common', 'status')" width="90" align="center">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column prop="remark" :label="t('common', 'remark')" show-overflow-tooltip align="center" />
          <el-table-column prop="create_time" :label="t('common', 'createTime')" :formatter="dateFormatter" align="center" />
          <el-table-column v-if="checkPermit(['system:tenant:update', 'system:tenant:delete'])" prop="operate" :label="t('common', 'operate')" :width="computedOperateWidth(['system:tenant:update', 'system:tenant:delete'])" align="center" fixed="right">
            <template #default="scope">
              <el-button v-if="checkPermit(['system:tenant:update'])" type="primary" icon="Edit" @click="openForm('update', scope.row.id)" />
              <el-button v-if="checkPermit(['system:tenant:delete']) && scope.row.packageId !== 0" type="danger" icon="Delete" @click="handleDelete(scope.row.id)" />
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageIndex" :total="total" :disabled="queryLoading" @pagination="getList" />
        <TenantForm ref="formRef" @success="getList" />
        <ExcelExportDialog ref="ExcelExportDialogRef" :filename="t('sys.tenant', 'manage')" :hasSelected="false" :fieldList="filedList" @success="exportDone" />
      </template>
    </ContentFormTable>
  </PageCard>
</template>

<style scoped lang="scss">
.el-table {
  width: 100%;
  height: 100%;
}
</style>
